from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests,functools
from application.models.users.user import *
from db import db
from tools.myredis import r
from tools.comm import get_ali_object
goods_blue = Blueprint("goodsblue", __name__)


@goods_blue.route('/addcart', methods=['POST'])
def addcart():
    # 获取参数
    data = json.loads(request.data)
    userid = data["userid"]
    goodsid = data["goodsid"]
    pkey = "cart" + str(userid)
    r.hash_add(pkey, goodsid, 1)
    return jsonify({"code": 200, "msg": "加入购物车成功"})


@goods_blue.route("/getcart")
def getcart():
    userid = request.args.get("userid")
    pkey = "cart" + str(userid)
    res = r.hash_getall(pkey)
    for i, j in res.items():
        goodsid = i.decode()
        sql = "select id,name,tcount,url from course where id=%d" % int(goodsid)
        res = db.findone(sql)
    return jsonify({"code": 200, "msg": "ok", "data": res})

@goods_blue.route("/addorder", methods=["POST"])
def addorder():
    data = json.loads(request.data)
    userid = int(data["userid"])
    courseid = int(data["courseid"])
    order_no = str(int(time.time())) + str(userid) + str(random.randint(100, 999))
    try:
        sql = "select * from course where id= %d" % courseid
        res = db.findone(sql)
        sum =res["tcount"]
        print('1111111111',sum)
        # 添加订单表
        create_time = datetime.datetime.strftime(
            datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql1 = "insert into orders(order_no,price,create_time,status,userid,courseid) values('%s','%s','%s',%d,%d,%d)" % (
            str(order_no), sum, str(create_time), 1, userid, courseid)
        db.add(sql1)
        db.commit()
        return jsonify({"code": 200, "msg": "OK"})
    except Exception as a:
        print(">>>>>>>>>>>>>>>>>>", a)
        db.rollback()
        return jsonify({"code": 400, "msg": "错误"})

@goods_blue.route('/getorder')
def getorder():
    userid = request.args.get("userid")
    sql = "select * from orders where id=%d" % int(userid)
    res = db.findAll(sql)
    for i in res:
        i["price"] = float(i["price"])
        i["create_time"] = datetime.datetime.strftime(i["create_time"], "%Y-%m-%d %H:%M:%S")
        return jsonify({"code": 200, "msg": "ok", "data": res})


@goods_blue.route("/orderpay")
def orderpay():
    userid = int(request.args.get("userid"))
    goodsid = int(request.args.get("goodsid"))
    sql = "select * from orders where id=%d" % (goodsid)
    goods = db.findone(sql)
    price = float(goods["price"])
    order_no = int(goods["order_no"])
    # 支付
    alipay = get_ali_object()
    # 生成支付的url
    query_params = alipay.direct_pay(
    subject=str(userid)+"购买课程服务",  # 商品简单描述
    out_trade_no=order_no, # 用户购买的商品订单号（每次不一样） 20180301073422891
    total_amount=price,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code": 200, "url": pay_url})